package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.RedisConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.*;
import com.sky.result.PageBean;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    /**
     * 菜品分页查询
     *
     * @param dishPageQueryDTO dto
     * @return pagebean对象
     */
    @Override
    public PageBean pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> dishVOPage = dishMapper.pageQuery(dishPageQueryDTO);
        return PageBean.builder()
                .total(dishVOPage.getTotal())
                .records(dishVOPage.getResult())
                .build();
    }


    /**
     * 新增菜品
     *
     * @param dishDTO dto
     */
    @Override
    @Transactional
    public void addDishWithFlavor(DishDTO dishDTO) {
        // 新增菜品 涉及到俩个表 dish表 和 dish_flavor表
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.insert(dish);

        // dish_flavor 表的添加(一个菜品对应多个口味)
        List<DishFlavor> flavors = dishDTO.getFlavors();
        flavors.forEach(flavor -> {
            flavor.setDishId(dish.getId());
            dishFlavorMapper.insert(flavor);
        });

        redisTemplate.delete(RedisConstant.DISH_LIST_CATEGORYID + dishDTO.getCategoryId());
    }

    /**
     * 批量删除菜品
     *
     * @param ids 菜品id集合
     */
    @Override
    @Transactional //事务
    public void deleteByIds(List<Long> ids) {
        for (Long id : ids) {
            // 1 在售状态的菜品不能删除
            Dish dish = dishMapper.selectById(id);
            if (dish.getStatus().equals(StatusConstant.ENABLE)) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
            // 2 被套餐关联了的菜品不能删除 (用菜品的id去查 setmeal_dish表)
            List<SetmealDish> setmealDishes = setmealDishMapper.selectByDishId(id);
            if (setmealDishes != null && setmealDishes.size() > 0) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
            }

            dishMapper.deleteById(id);
            // 同时也得删除对应 dish_flavor表中的数据
            dishFlavorMapper.deleteByDishId(id);
        }
        Set keys = redisTemplate.keys(RedisConstant.DISH_LIST_CATEGORYID + "*");
        redisTemplate.delete(keys);
    }


    /**
     * 根据id查询菜品详情
     *
     * @param id 菜品id
     * @return dishvo
     */
    @Override
    public DishVO getByIdWithFlavor(Long id) {
        return dishFlavorMapper.getByIdWithFlavor(id);
    }


    /**
     * 修改菜品信息
     *
     * @param dishDTO dto
     */
    @Override
    public void updateWithFlavor(DishDTO dishDTO) {
        // 得修改dish表和dish_flavor表, 一个菜品对应多个口味,先把原来菜品的口味全部删掉再添加
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.update(dish);
        // 口味表
        // 删除原有的口味数据
        dishFlavorMapper.deleteByDishId(dish.getId());
        List<DishFlavor> flavors = dishDTO.getFlavors();
        flavors.forEach(dishFlavor -> {
            dishFlavor.setDishId(dish.getId());
            dishFlavorMapper.insert(dishFlavor);
        });
        Set keys = redisTemplate.keys(RedisConstant.DISH_LIST_CATEGORYID + "*");
        redisTemplate.delete(keys);
    }

    /**
     * 菜品起售、停售
     *
     * @param status 菜品的状态
     * @param id     菜品的id
     */
    @Override
    @Transactional
    public void updateStatus(Integer status, Long id) {
        Dish dish = Dish.builder()
                .status(status)
                .id(id).build();
        // 更新菜品信息
        dishMapper.update(dish);
        // 如果停售当前菜品,则相关的套餐也得停售
        // 根据菜品id查询套餐
        List<SetmealDish> setmealDishes = setmealDishMapper.selectByDishId(id);
        if (status.equals(StatusConstant.DISABLE)) {
            setmealDishes.forEach(setmealDish -> {
                Long setmealId = setmealDish.getSetmealId();
                Setmeal setmeal = Setmeal.builder()
                        .id(setmealId)
                        .status(status)
                        .build();
                setmealMapper.update(setmeal);
            });
        }
        Set keys = redisTemplate.keys(RedisConstant.DISH_LIST_CATEGORYID + "*");
        redisTemplate.delete(keys);
    }

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId 分类id
     * @return 菜品集合
     */
    @Override
    @Cacheable(cacheNames = "dish:list:categoryID", key = "#categoryId")
    public List<Dish> selectByCategoryId(Long categoryId) {
        return dishMapper.selectByCategoryId(categoryId);
    }

    /**
     * 根据分类id查询菜品(起售状态的菜品,包含菜品口味)
     *
     * @param categoryId 分类id
     * @return dishvo集合
     */
    @Override
    @Cacheable()
    public List<DishVO> selectWithFlavorByCategoryId(Long categoryId) {
        String redisKey = RedisConstant.DISH_LIST_CATEGORYID + categoryId.toString();
        // 当第一次查询某个分类的菜品时，会从数据库中进行查询，同时将查询的结果存储到Redis中，在后绪的访问，若查询相同分类的菜品时，直接从Redis缓存中查询，不再查询数据库。

        // 1.先查询redis缓存数据
        List<DishVO> redisData = (List<DishVO>) redisTemplate.opsForValue().get(redisKey);
        if (redisData != null) {
            return redisData;
        }
        // 2.再去查询数据库
        List<DishVO> dishVOS = dishMapper.selectWithFlavorByCategoryId(categoryId);
        // 3.把数据存到redis中去
        if (dishVOS.size() == 0) {
            return dishVOS;
        } else {
            redisTemplate.opsForValue().set(redisKey, dishVOS);
            return dishVOS;
        }
    }
}
